#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'xnevergreen'
__mtime__ = '2015-12-23'
# code is far away from bugs with the god animal protecting
    I love animals. They taste delicious.
              ┏┓      ┏┓
            ┏┛┻━━━┛┻┓
            ┃      ☃      ┃
            ┃  ┳┛  ┗┳  ┃
            ┃      ┻      ┃
            ┗━┓      ┏━┛
                ┃      ┗━━━┓
                ┃  神兽保佑    ┣┓
                ┃  永无BUG！   ┏┛
                ┗┓┓┏━┳┓┏┛
                  ┃┫┫  ┃┫┫
                  ┗┻┛  ┗┻┛
"""

from selenium import webdriver
import requests
import re, time, sys, os, json, random, string

# 去除ssl的警告信息
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

username = 'xnevergreen@163.com'
password = 'xxx'

UA = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36"

VIP_URL = 'https://vip.jd.com/'
LOGIN_URL = 'https://passport.jd.com/loginservice.aspx?callback=jQuery{NUM}&method=Login&_={TIMESTAMP}'
SIGN_URL = 'https://vip.jd.com/common/signin.html?token={TOKEN}'

LOGINUSERNAME = '//*[@id="loginname"]' # 用户名
LOGINPASSWORD = '//*[@id="nloginpwd"]' # 密码
AUTHCODEIMG = '//*[@id="JD_Verification1"]' # 验证码图片
LOGINAUTHCODE = '//*[@id="authcode"]' # 验证码
LOGINSUBMITBUTTON = '//*[@id="loginsubmit"]' # 登录按钮
SIGNBUTTON = '//*[@id="checkinBtn"]/i' # 签到领京豆按钮

# 获取脚本所在真实目录
strfilepath = os.path.realpath(__file__)
COOKIE_PATH = "%s/" % (os.path.dirname(strfilepath),)
COOKIEFILE = COOKIE_PATH + "tmp/cookie_" + username

def getTime():
    return str(int(time.time()))

s = requests.session()
sel = webdriver.Chrome()
# sel = webdriver.PhantomJS()

if os.path.exists(COOKIEFILE):
    # 存在cookie则更新cookie
    cookie = {}
    with open(COOKIEFILE) as f:
        cookies = json.load(f)
    # 转化selenium的cookie为request所使用的cookie
    for info in cookies:
        cookie[info['name']] = info['value']
    s.cookies.update(cookie)

    # 获取token
    headers = {
        "User-Agent" : UA,
        "Pragma" : "no-cache",
        "Host" : "vip.jd.com",
        "Referer" : "http://vip.jd.com/"
    }
    vipReq = s.get(VIP_URL, headers=headers, cookies=cookie, verify=False)
    # print vipReq.text
    getToken = re.compile(r'pageConfig.token="(.*?)";', re.S)
    content = re.findall(getToken, vipReq.text)
    token = str(content[0])

    # 验证登录
    headers = {
        "User-Agent" : UA,
        "Pragma" : "no-cache",
        "Host" : "passport.jd.com",
        "Referer" : "http://vip.jd.com/"
    }
    LOGIN_URL = LOGIN_URL.replace('{TIMESTAMP}', str(int(time.time())*1000))
    randomNum = [random.choice(string.digits) for i in range(7)]
    randomStr = ''.join([i for i in randomNum])
    LOGIN_URL = LOGIN_URL.replace('{NUM}', randomStr)
    print 'login url: ' + LOGIN_URL
    loginReq = s.get(LOGIN_URL, headers=headers, cookies=cookie, verify=False)
    print 'login result: ' + loginReq.text.encode('utf-8')
    print 'login cookie: ' + str(s.cookies.get_dict())

    # 执行签到命令
    headers = {
        "User-Agent" : UA,
        "Pragma" : "no-cache",
        "Host" : "vip.jd.com",
        "Referer" : "https://vip.jd.com/"
    }
    SIGN_URL = SIGN_URL.replace('{TOKEN}', token)
    print 'sign url: ' + SIGN_URL
    getReq = s.get(SIGN_URL, verify=False)
    print 'sign result: ' + getReq.text.encode('utf-8')
else:
    sel.maximize_window()
    loginurl = 'https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fvip.jd.com%2F'
    #open the login in page
    sel.get(loginurl)
    time.sleep(6)

    #sign in the username
    try:
        sel.find_element_by_xpath(LOGINUSERNAME).send_keys(username)
        print 'username success - (^_^)'
    except:
        print 'username fail - (X_X)'
    time.sleep(1)
    #sign in the pasword
    try:
        sel.find_element_by_xpath(LOGINPASSWORD).send_keys(password)
        print 'password success - (^_^)'
    except:
        print 'password fail - (X_X)'
    time.sleep(1)
    #click to login
    try:
        sel.find_element_by_xpath(LOGINSUBMITBUTTON).click()
        print 'login button click success - (^_^)'
    except:
        print 'login button click fail - (X_X)'
    time.sleep(3)

    # 验证登录成功与否，若currenturl发生变化，则认为登录成功
    curpage_url = sel.current_url
    print curpage_url
    while(curpage_url == loginurl):
        #print 'please input the verify code:'
        print 'please input the verify code:'
        verify_url = 'https:' + sel.find_element_by_xpath(AUTHCODEIMG).get_attribute("src2")
        img = s.get(verify_url)
        f = open(COOKIE_PATH + 'tmp/image.jpg', 'wb')
        f.write(img.content)
        f.close()
        print 'input code:'
        os.system('start tmp/image.jpg')
        verifycode = sys.stdin.readline()
        sel.find_element_by_xpath(LOGINAUTHCODE).send_keys(verifycode)
        try:
            sel.find_element_by_xpath(LOGINSUBMITBUTTON).click()
            print 'login button click success - (^_^)'
        except:
            print 'login button click fail - (X_X)'
        time.sleep(3)
        curpage_url = sel.current_url

    # 判断是否已经领过京豆
    try:
        SignText = sel.find_element_by_xpath(SIGNBUTTON).get_attribute('innerHTML')
        bExist = True
    except:
        bExist = False
    if bExist == False:
        print 'Already Signed (^_^)'
        # 关闭浏览器
        sel.quit()
        sys.exit(0)

    # 通过对象的方法获取当前访问网站的session  cookie
    cookie = [item["name"] + "=" + item["value"] for item in sel.get_cookies()]
    #print cookie
    cookiestr = ';'.join(item for item in cookie)
    print cookiestr
    with open(COOKIEFILE, 'w') as f:
        json.dump(sel.get_cookies(), f)
    # 模拟签到
    try:
        sel.find_element_by_xpath(SIGNBUTTON).click()
        print 'get bean success - (^_^)'
        bExit = True
    except:
        print 'get bean fail - (X_X)'
        bExit = False

    if bExit == True:
        time.sleep(10)
    # 关闭浏览器
    sel.quit()
